using UnityEngine;

namespace Voodoo.Meta
{
	public class LeaderboardRankLogic
	{
		private readonly LeaderboardRankData _data;

		public int PlayerRank { get; private set; }

		public int PreviousRank { get; private set; }

		public int NewRank { get; private set; }

		public int RankStep { get; private set; }

		public int PreviousScore { get; private set; }

		public int NewScore { get; private set; }

		public bool RankUp { get; private set; }

		public LeaderboardRankLogic(LeaderboardRankData data)
		{
			_data = data;
		}

		public void Initialize(int previousScore, int newScore)
		{
			PreviousScore = previousScore;
			NewScore = newScore;
			RankUp = NewScore > PreviousScore;
			PlayerRank = GetPlayerRank();
			PreviousRank = PlayerRank;
			RankStep = GetRankEarned(newScore);
			NewRank = GetNextRankFromStep(previousScore, newScore, RankStep);
		}

		public int GetPlayerRank()
		{
			return NintendoPlayerPrefs.GetInt("LeaderboardPlayerRank", _data.playerStartRank);
		}

		public int GetNextRank(int previousScore, int newScore)
		{
			int rankEarned = GetRankEarned(newScore);
			return GetNextRankFromStep(previousScore, newScore, rankEarned);
		}

		public int GetNextRankFromStep(int previousScore, int newScore, int rankStep)
		{
			int num = ((newScore <= previousScore) ? 1 : (-1));
			return PlayerRank + rankStep * num;
		}

		public LeaderboardBackgroundColors GetPlayerBackgroundsColors()
		{
			return GetBackgroundColorsByRank(NewRank, isPlayer: true);
		}

		public LeaderboardBackgroundColors GetBackgroundColorsByRank(int rank, bool isPlayer = false)
		{
			return _data.GetBackgroundColorsByRank(rank, isPlayer);
		}

		public Sprite GetPlayerMedal()
		{
			return GetMedalByRank(NewRank);
		}

		public Sprite GetMedalByRank(int rank)
		{
			return _data.GetMedalByRank(rank);
		}

		public void SaveNewRank()
		{
			NintendoPlayerPrefs.SetInt("LeaderboardPlayerRank", NewRank);
		}

		public int GetRankEarned(int newScore)
		{
			int num = _data.GetRankForScore(newScore);
			int num2 = 1;
			if (_data.allowRankClamp)
			{
				num = Mathf.Clamp(num, _data.rankClampRange.x, _data.rankClampRange.y);
			}
			if (PlayerRank - num < num2)
			{
				num = PlayerRank - num2;
			}
			return num;
		}
	}
}
